package com.yufei.infoExtractor.pfw.mongodb;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.yufei.infoExtractor.core.InfoExtractorMI;
import com.yufei.infoExtractor.pfw.InfoExtractorDao;
import com.yufei.infoExtractor.pfw.entity.Entity;
import com.yufei.infoExtractor.pfw.entity.News;
import com.yufei.infoExtractor.pfw.entity.Weibo;
import com.yufei.infoExtractor.util.AppUtil;
import com.yufei.infoExtractor.util.CommonUtil;

@Repository
public class DataRepository {
	@Autowired
	MongoOperations mongoOperations;
	@Autowired
	MongoDbFactory mongoDbFactory;
	/**
	 * @param obj
	 * save entity that has annotion into the collection 
	 */
	public void save(Object obj){
		String collectionName=obj.getClass().getSimpleName().toLowerCase();
		if(!mongoOperations.collectionExists(collectionName)){
			mongoOperations.createCollection(collectionName);
		}
		mongoOperations.save(obj);
		}
	
	//批量插入新数据，确保数据没有被保存过
	public void insert(Collection objs){
		if(CommonUtil.isEmptyOrNull(objs)){
			throw new IllegalArgumentException();
		}
		Iterator<Object> iterator = objs.iterator();
		Object obj=iterator.next();
	
		String collectionName=obj.getClass().getSimpleName().toLowerCase();
		if(!mongoOperations.collectionExists(collectionName)){
			mongoOperations.createCollection(collectionName);
		}
		mongoOperations.insertAll(objs);
		}
	//save the entity into a customer collectionName
	public void save(Object obj,String collectionName){
		
		if(!mongoOperations.collectionExists(collectionName)){
			mongoOperations.createCollection(collectionName);
		}
		mongoOperations.save(obj);
	}
	//query a entity form the collection whose collectionname is the entity's class name
	public  <T> T queryEntity(String queryParameter,Object queryValue,Class<T> cla){
		List<T> list= mongoOperations.find(query(where(queryParameter).is(queryValue)), cla);
		if(CommonUtil.isEmptyOrNull(list)){
			return null;
		}
		return 		(T)list.get(0);
	}
	public <T> List<T> queryListEntity(String queryParameter,Object queryValue,Class<T> cla){
		List<T> entitys=null;
		entitys=(List<T>) mongoOperations.find(query(where(queryParameter).is(queryValue)), cla);
		return entitys;
	}
	/**
	 * @param sign:唯一的描述实体，比ID更能生动的描述该实体
	 * @param entity：查询实体
	 * @return
	 */
	public <T> List<T> queryBySign(String sign,Class<T> entity){
		return mongoOperations.find(query(where("sign").is(sign)), entity);
		

		
	}
   public void updateEntity(String id,Class entity,String property,Object value){
	   
	   mongoOperations.updateFirst(query(where("id").is(id)), new Update().update(property, value), entity);
	   
   }
   
   //查询所有特定集合中的某个字段
   public List queryAllValuesOfField(String fieldName,Class entity,Map queryMap){
          List result=new ArrayList();
          BasicDBObject fields=new BasicDBObject();
	    fields.put(fieldName, 1);
	    DBCursor dbCursor=mongoOperations.getCollection(CommonUtil.downFirstChar(entity.getSimpleName()))
	    .find(new BasicDBObject(queryMap),fields);
	    while(dbCursor.hasNext()){
	    	result.add(dbCursor.next().get(fieldName));
	    }
	  dbCursor.close();
return result;	   
   }
	public MongoOperations getMongoOperations(){
		return mongoOperations;
	}

	public void setMongoOperations(MongoOperations mongoOperations) {
		this.mongoOperations = mongoOperations;
	}
	//save file
	//public void 
	public MongoDbFactory getMongoDbFactory() {
		return mongoDbFactory;
	}
	public void setMongoDbFactory(MongoDbFactory mongoDbFactory) {
		this.mongoDbFactory = mongoDbFactory;
	}
	/**删除entity实体
	 * @param entity
	 */
	public void removeEntity(Entity entity){
		String _id = entity.getId();

		if(CommonUtil.isEmptyOrNull(_id)){
			throw new IllegalArgumentException();
			
		}
		DBObject dbobject=new BasicDBObject();
		ObjectId id=new ObjectId(_id);
		dbobject.put("_id", id);
		String downFirstChar = CommonUtil.downFirstChar(entity.getClass().getSimpleName());
		this.mongoDbFactory.getDb().getCollection(downFirstChar).remove(dbobject);
		
		
	}
	
public static  void main(String[] args){
		
	/*	

InfoExtractorMI infoExtractorMI=(InfoExtractorMI) AppUtil.getBeanFromBeanContainer(InfoExtractorMI.class);
infoExtractorMI.exportEntityToXml("com.yufei.infoExtractor.pfw.entity.News", AppUtil.getInfoExtractorConfig().getTempDirectory());*/
InfoExtractorDao	infoExtractorDao=(InfoExtractorDao) AppUtil.getBeanFromBeanContainer(InfoExtractorDao.class);
		Weibo weibo=new Weibo();
		
		java.util.List list=new ArrayList();
		list.add("test");
		weibo.setContents(list);
		weibo.setUserName("jasstion");
		weibo.setSign("weibo");
		weibo.setHashCode("458935nknskdfu9ou5kn3k");
		weibo=(Weibo) infoExtractorDao.saveEntityWithReturnValue(weibo);
		String preid=weibo.getId();
		weibo.setUserName("afei");
		weibo=(Weibo) infoExtractorDao.saveEntityWithReturnValue(weibo);
		String nowid=weibo.getId();
		System.out.print(nowid==preid);
		/*Weibo weibo1= datar.queryBySign("weibo", Weibo.class).get(0);
        System.out.print(weibo1.getId());

		System.out.print(weibo1.getContents().size()+"\n");
		weibo1.getContents().add("test");
		datar.save(weibo1);
		System.out.print(weibo1.getContents().size()+"\n");
         Weibo weibo2=(Weibo) datar.queryEntity("userName", weibo.getUserName(), Weibo.class);
         for(String str:weibo2.getContents()){
        	 System.out.print(str+"\n");
         }
         		datar.getMongoOperations().dropCollection("weibo");

         System.out.print(weibo2.getId());*/
	}
}
